package com.spring.provideronetest.Utils;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther zhangxiangtao
 * @date 2021/1/15
 */
@Data
@Component
public class JsonResult<T> {
	private static final long serialVersionUID =-123847128341023033L;
	@JSONField
	private boolean success = true;
	@JSONField
	private String message = null;
	@JSONField
	private String errorCode = "0";
	@JSONField
	private String errorMsg = "操作成功";
	@JSONField
	private Integer total = 0;
	@JSONField
	private List<T> data = new ArrayList();

	private JsonResult() {

	}
	/**
	 *  虽然很多人都写为isSuccess(),但强烈不建议，因为相当于getSuccess()
	 *  可以用idea的自动生成下，如果有isSuccess()，就不会生成getSuccess()
	 */
	public boolean successFlag() {
		return success;
	}
	public JsonResult(T data) {
		if (data != null) {
			this.data.add(data);
		}
	}
	public JsonResult(List<T> data) {
		if (data != null && data.size() > 0) {
			this.data = data;
		}
	}
	public static JsonResult ok(){
		return new JsonResult();
	}
	public static<T> JsonResult ok(List<T> data){
		JsonResult jsonResult = new JsonResult();
		if (data != null && data.size() > 0) {
			jsonResult.data = data;
		}
		return jsonResult;
	}
	public static<T> JsonResult ok(T data){
		JsonResult jsonResult = new JsonResult();
		if (data != null) {
			jsonResult.data.add(data);
		}
		return jsonResult;
	}
	public static<T> JsonResult ok(String string){
		JsonResult jsonResult = new JsonResult();
		jsonResult.setErrorMsg(string);
		return jsonResult;
	}
	public static JsonResult fail(String errorCode,String errorMsg){
		JsonResult jsonResult = new JsonResult();
		jsonResult.setSuccess(false);
		jsonResult.setErrorCode(errorCode);
		jsonResult.setErrorMsg(errorMsg);
		return jsonResult;
	}

	/**
	 * 当有异常时，直接throw一个实现ErrorCode的异常类
	 * 通过global异常处理器，就可以把jsonResult封装起来，这样代码简洁优美
	 * 如果没有BaseException可以注释掉这个方法
	 */
//    public static JsonResult fail(BaseException exception){
//        JsonResult jsonResult = new JsonResult();
//        if (exception != null) {
//            jsonResult.success = false;
//            jsonResult.errorCode = exception.getErrorCode();
//            jsonResult.errorMsg = exception.getErrorMsg();
//        }
//        return jsonResult;
//    }

}
